package com.open.basic.util;

import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;


/**
 * @author: system
 * @Date: 2025/1/21 下午2:44
 * @Version: V1.0
 * @description: | 懒加载构建
 */

public class LazyBuilder<T> implements Supplier<T> {

    private final Supplier<T> supplier;

    private T value;

    public LazyBuilder(Supplier<T> supplier) {
        this.supplier = supplier;
    }

    public static <T> LazyBuilder<T> build(Supplier<T> supplier) {
        return new LazyBuilder<>(supplier);
    }

    @Override
    public T get() {
        return orElse(null);
    }

    public T orElse(T defaultValue) {
        // 缓存值不存在，重新查询
        if (Objects.isNull(value)) {
            value = Optional.ofNullable(supplier.get()).orElse(defaultValue);
        }
        return value;
    }

    public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
        // 缓存值不存在，重新查询
        if (Objects.isNull(value)) {
            value = Optional.ofNullable(supplier.get()).orElseThrow(exceptionSupplier);
        }
        return value;
    }

    public <S> LazyBuilder<S> map(Function<T, S> function) {
        return LazyBuilder.build(() -> function.apply(get()));
    }

}


